﻿using System;
using System.Diagnostics;
using Microsoft.Office.Core;

using Application = Microsoft.Office.Interop.Word.Application;

namespace Zalgo.Word
{
    public partial class ThisAddIn
    {
        private Application _myApplication;
        private CommandBarButton _myControl;

        private void ThisAddInStartup(object sender, EventArgs e)
        {
            _myApplication = Application;

            RemoveExistingMenuItem();
            AddMenuItem();
        }

        private void RemoveExistingMenuItem()
        {
            var contextMenu = _myApplication.CommandBars["Text"];

            var control = (CommandBarButton)contextMenu.FindControl
                (MsoControlType.msoControlButton, missing,
                "ZalgoMenuItem", true, true);

            if ((control != null))
            {
                control.Delete(true);
            }
        }

        private void AddMenuItem()
        {
            const MsoControlType menuItem = MsoControlType.msoControlButton;

            _myControl = (CommandBarButton)_myApplication.CommandBars["Text"].Controls.Add
                (menuItem, missing, missing, 1, true);

            _myControl.Style = MsoButtonStyle.msoButtonCaption;
            _myControl.Caption = "He comes!".ToZalgo();
            _myControl.Tag = "ZalgoMenuItem";

            _myControl.Click += ZalgoControlClick;
        }

        Random _rnd = new Random();

        void ZalgoControlClick(CommandBarButton ctrl, ref bool cancelDefault)
        {
            var range = Globals.ThisAddIn.Application.Selection.Range;
            var curr = range.Start;
            var letters = range.End - range.Start;
            float fontChange = _rnd.Next(-3, 3);

            for (var i = 0; i < letters; i++)
            {
                _myApplication.Selection.SetRange(curr + i, curr + i + 1);
                Debug.Print("letter => '" + _myApplication.Selection.Text + "' size: " + _myApplication.Selection.Font.Size);
                if(_myApplication.Selection.Text == " ")
                {
                    fontChange = _rnd.Next(-3, 6);
                }
                _myApplication.Selection.Font.Size += fontChange;
                var zalgo = Zalgo.GetZalgo();
                _myApplication.Selection.InsertAfter(zalgo);
                curr += zalgo.Length;
            }
        }

        private void ThisAddInShutdown(object sender, EventArgs e)
        {

        }

        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            Startup += ThisAddInStartup;
            Shutdown += ThisAddInShutdown;
        }

        #endregion

    }
}
